<template>
  <el-dialog
    v-model="dialogVisible"
    :title="roleData ? '编辑角色' : '新增角色'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="right">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入角色名称" maxlength="50" show-word-limit />
      </el-form-item>
      <el-form-item label="角色编码" prop="code">
        <el-input
          v-model="form.code"
          placeholder="请输入角色编码"
          maxlength="50"
          show-word-limit
          :disabled="!!roleData"
        />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="请输入角色描述"
          maxlength="200"
          show-word-limit
          :rows="3"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="true">启用</el-radio>
          <el-radio :value="false">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="form.sort"
          :min="0"
          :max="999"
          controls-position="right"
          style="width: 200px"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { createRole, updateRole } from "@/api/role";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  roleData: {
    type: Object,
    default: null,
  },
});

const emit = defineEmits(["update:modelValue", "success"]);

const formRef = ref();
const loading = ref(false);

const form = reactive({
  name: "",
  code: "",
  description: "",
  status: true,
  sort: 0,
});

const rules = {
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    {
      min: 2,
      max: 50,
      message: "角色名称长度在 2 到 50 个字符",
      trigger: "blur",
    },
  ],
  // 角色编码只能为英文
  code: [
    { required: true, message: "请输入角色编码", trigger: "blur" },
    {
      pattern: /^[A-Za-z_][A-Za-z0-9_]*$/,
      message: "角色编码只能为英文",
      trigger: "blur",
    },
  ],
  description: [
    { max: 200, message: "角色描述长度不能超过 200 个字符", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  sort: [
    { required: true, message: "请输入排序", trigger: "blur" },
    { type: "number", message: "排序必须为数字", trigger: "blur" },
  ],
};

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

const resetForm = () => {
  Object.assign(form, {
    name: "",
    code: "",
    description: "",
    status: true,
    sort: 0,
  });
  formRef.value?.resetFields();
};

// 监听角色数据变化，填充表单
watch(
  () => props.roleData,
  (newVal) => {
    if (newVal) {
      Object.assign(form, {
        name: newVal.name || "",
        code: newVal.code || "",
        description: newVal.description || "",
        status: newVal.status !== undefined ? newVal.status : true,
        sort: newVal.sort || 0,
      });
    } else {
      resetForm();
    }
  },
  { immediate: true }
);

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;

    const submitData = { ...form };

    if (props.roleData) {
      // 编辑模式
      await updateRole(props.roleData.id, submitData);
      ElMessage.success("角色更新成功");
    } else {
      // 新增模式
      await createRole(submitData);
      ElMessage.success("角色创建成功");
    }

    emit("success");
    handleClose();
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error(props.roleData ? "角色更新失败" : "角色创建失败");
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>